package obth;

import java.util.concurrent.BlockingQueue;

public class PageThread implements Runnable{

    private BlockingQueue<PageEvent> fromQueue;
    private BlockingQueue<ReqRes> toQueue;

    public PageThread(BlockingQueue<PageEvent> fromQueue, BlockingQueue<ReqRes> toQueue) {

        this.fromQueue = fromQueue;
        this.toQueue = toQueue;
    }

    @Override
    public void run() {
            while (true){
            try {
                PageEvent event = fromQueue.take();
                if (event instanceof UserPageEvent){
                    UserPageEvent e = (UserPageEvent) event;


                    ReqRes reqRes = new ReqRes();
                    reqRes.setRequestId("reqId_"+e.getK());
                    reqRes.setContentType("application/json");
                    String data = String.format("{'name':'lisi','age':%d}", e.getK());
                    reqRes.setDataToSend(data);
                    reqRes.setContentLength(data.length());
                    reqRes.setSuccess((reqRes1)->{
                        Tool.debug("回调函数"+reqRes1.getDataToRecv());
                        ReqRes reqRes2 = new ReqRes();
                        reqRes2.setDataToSend(reqRes1.getDataToRecv());
                        reqRes2.setSuccess((r)->{
                            Tool.debug("回调地狱");
                        });
                        try {
                            toQueue.put(reqRes2);
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                        }
                    });

                    toQueue.put(reqRes);
                    continue;
                }
                if (event instanceof ReqResPageEvent){

                    ReqResPageEvent pageEvent = (ReqResPageEvent) event;
                    Tool.debug(pageEvent.getTimestamp());
                    ReqRes reqRes = pageEvent.getReqRes();
                    reqRes.getSuccess().accept(reqRes);

                    continue;
                }

            } catch (InterruptedException e) {

                    e.printStackTrace();
            }

        }
    }
}
